/**
 * 系统信息工具类
 * 用于获取App端的系统信息，包括状态栏高度、安全区域等
 */

class SystemInfo {
  constructor() {
    this.systemInfo = null
    this.statusBarHeight = 0
    this.safeAreaInsets = null
  }

  /**
   * 检查是否为App环境
   * @returns {Boolean} 是否为App环境
   */
  isAppEnvironment() {
    return typeof plus !== 'undefined'
  }

  /**
   * 获取系统信息
   * @returns {Promise} 系统信息
   */
  async getSystemInfo() {
    return new Promise((resolve, reject) => {
      if (this.isAppEnvironment()) {
        // App端获取系统信息
        this.getAppSystemInfo().then(resolve).catch(reject)
      } else {
        // H5端获取系统信息
        uni.getSystemInfo({
          success: (res) => {
            this.systemInfo = res
            resolve(res)
          },
          fail: reject
        })
      }
    })
  }

  /**
   * 获取App端系统信息
   * @returns {Promise} 系统信息
   */
  async getAppSystemInfo() {
    return new Promise((resolve, reject) => {
      try {
        const systemInfo = {
          platform: plus.os.name,
          system: plus.os.version,
          version: plus.runtime.version,
          model: plus.device.model,
          brand: plus.device.vendor,
          pixelRatio: plus.screen.scale,
          screenWidth: plus.screen.resolutionWidth,
          screenHeight: plus.screen.resolutionHeight,
          windowWidth: plus.screen.resolutionWidth,
          windowHeight: plus.screen.resolutionHeight,
          statusBarHeight: plus.navigator.getStatusbarHeight(),
          safeAreaInsets: this.getSafeAreaInsets(),
          language: plus.os.language,
          fontSizeSetting: plus.os.fontSize,
          albumAuthorized: plus.navigator.checkPermission('android.permission.READ_EXTERNAL_STORAGE') === 'granted',
          cameraAuthorized: plus.navigator.checkPermission('android.permission.CAMERA') === 'granted',
          locationAuthorized: plus.navigator.checkPermission('android.permission.ACCESS_FINE_LOCATION') === 'granted',
          microphoneAuthorized: plus.navigator.checkPermission('android.permission.RECORD_AUDIO') === 'granted',
          notificationAuthorized: plus.navigator.checkPermission('android.permission.VIBRATE') === 'granted',
          phoneCalendarAuthorized: plus.navigator.checkPermission('android.permission.READ_CALENDAR') === 'granted',
          bluetoothEnabled: plus.bluetooth.getState() === 'on'
        }

        this.systemInfo = systemInfo
        this.statusBarHeight = systemInfo.statusBarHeight
        resolve(systemInfo)
      } catch (error) {
        reject(new Error(`获取系统信息失败: ${error.message}`))
      }
    })
  }

  /**
   * 获取状态栏高度
   * @returns {Number} 状态栏高度
   */
  getStatusBarHeight() {
    if (this.isAppEnvironment()) {
      try {
        return plus.navigator.getStatusbarHeight()
      } catch (error) {
        console.error('获取状态栏高度失败:', error)
        return 0
      }
    } else {
      // H5端返回默认值
      return this.systemInfo?.statusBarHeight || 0
    }
  }

  /**
   * 获取安全区域信息
   * @returns {Object} 安全区域信息
   */
  getSafeAreaInsets() {
    if (this.isAppEnvironment()) {
      try {
        // 获取安全区域信息
        const display = plus.screen.getMainScreen()
        const safeAreaInsets = {
          top: plus.navigator.getStatusbarHeight(),
          bottom: 0,
          left: 0,
          right: 0
        }

        // 检查是否有底部安全区域（如iPhone X系列的Home指示器）
        if (plus.os.name === 'iOS') {
          // iOS设备可能有底部安全区域
          const screenHeight = plus.screen.resolutionHeight
          const windowHeight = plus.screen.resolutionHeight
          if (screenHeight > windowHeight) {
            safeAreaInsets.bottom = screenHeight - windowHeight
          }
        }

        return safeAreaInsets
      } catch (error) {
        console.error('获取安全区域失败:', error)
        return {
          top: this.getStatusBarHeight(),
          bottom: 0,
          left: 0,
          right: 0
        }
      }
    } else {
      // H5端返回默认值
      return this.systemInfo?.safeAreaInsets || {
        top: 0,
        bottom: 0,
        left: 0,
        right: 0
      }
    }
  }

  /**
   * 获取屏幕信息
   * @returns {Object} 屏幕信息
   */
  getScreenInfo() {
    if (this.isAppEnvironment()) {
      try {
        return {
          width: plus.screen.resolutionWidth,
          height: plus.screen.resolutionHeight,
          scale: plus.screen.scale,
          density: plus.screen.density
        }
      } catch (error) {
        console.error('获取屏幕信息失败:', error)
        return {
          width: 0,
          height: 0,
          scale: 1,
          density: 1
        }
      }
    } else {
      return {
        width: this.systemInfo?.screenWidth || 0,
        height: this.systemInfo?.screenHeight || 0,
        scale: this.systemInfo?.pixelRatio || 1,
        density: 1
      }
    }
  }

  /**
   * 获取设备信息
   * @returns {Object} 设备信息
   */
  getDeviceInfo() {
    if (this.isAppEnvironment()) {
      try {
        return {
          model: plus.device.model,
          vendor: plus.device.vendor,
          uuid: plus.device.uuid,
          imei: plus.device.imei,
          imsi: plus.device.imsi,
          platform: plus.os.name,
          version: plus.os.version,
          language: plus.os.language,
          fontSize: plus.os.fontSize
        }
      } catch (error) {
        console.error('获取设备信息失败:', error)
        return {
          model: 'Unknown',
          vendor: 'Unknown',
          uuid: '',
          imei: '',
          imsi: '',
          platform: 'Unknown',
          version: 'Unknown',
          language: 'Unknown',
          fontSize: 'normal'
        }
      }
    } else {
      return {
        model: this.systemInfo?.model || 'Unknown',
        vendor: this.systemInfo?.brand || 'Unknown',
        uuid: '',
        imei: '',
        imsi: '',
        platform: this.systemInfo?.platform || 'Unknown',
        version: this.systemInfo?.system || 'Unknown',
        language: this.systemInfo?.language || 'Unknown',
        fontSize: this.systemInfo?.fontSizeSetting || 'normal'
      }
    }
  }

  /**
   * 获取网络信息
   * @returns {Object} 网络信息
   */
  getNetworkInfo() {
    if (this.isAppEnvironment()) {
      try {
        return {
          networkType: plus.networkinfo.getCurrentType(),
          isConnected: plus.networkinfo.isConnected()
        }
      } catch (error) {
        console.error('获取网络信息失败:', error)
        return {
          networkType: 'unknown',
          isConnected: false
        }
      }
    } else {
      return {
        networkType: this.systemInfo?.networkType || 'unknown',
        isConnected: true
      }
    }
  }

  /**
   * 检查是否为全面屏设备
   * @returns {Boolean} 是否为全面屏设备
   */
  isFullScreenDevice() {
    const safeAreaInsets = this.getSafeAreaInsets()
    return safeAreaInsets.top > 20 || safeAreaInsets.bottom > 0
  }

  /**
   * 检查是否为刘海屏设备
   * @returns {Boolean} 是否为刘海屏设备
   */
  isNotchDevice() {
    const safeAreaInsets = this.getSafeAreaInsets()
    return safeAreaInsets.top > 20
  }

  /**
   * 获取导航栏高度（状态栏 + 导航栏）
   * @returns {Number} 导航栏高度
   */
  getNavigationBarHeight() {
    const statusBarHeight = this.getStatusBarHeight()
    // 通常导航栏高度为44px，加上状态栏高度
    return statusBarHeight + 44
  }

  /**
   * 获取底部安全区域高度
   * @returns {Number} 底部安全区域高度
   */
  getBottomSafeAreaHeight() {
    const safeAreaInsets = this.getSafeAreaInsets()
    return safeAreaInsets.bottom
  }

  /**
   * 初始化系统信息
   * @returns {Promise} 初始化结果
   */
  async init() {
    try {
      await this.getSystemInfo()
      console.log('系统信息初始化成功:', this.systemInfo)
      return this.systemInfo
    } catch (error) {
      console.error('系统信息初始化失败:', error)
      throw error
    }
  }
}

// 创建单例实例
const systemInfo = new SystemInfo()

export default systemInfo
